package com.aos.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StreamUtils;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

@Slf4j
//@Configuration
public class AuthGlobalFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return "post";
    }

    @Override
    public int filterOrder() {
        return 999;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        try {
            RequestContext ctx = RequestContext.getCurrentContext();
            InputStream stream = ctx.getResponseDataStream();
            String response = StreamUtils.copyToString(stream, Charset.forName("UTF-8"));
            if (StringUtils.isNotBlank(response) && response.contains("invalid_token")) {
                //Result result = Result.error(401, "Token 认证失败");
                ctx.setResponseBody(response);
                ctx.setResponseStatusCode(200);
            }else {
                ctx.setResponseBody(response);
            }
        }catch (IOException e){
            log.error("网关 Filter IO 异常",e);
        }
        return null;
    }
}
